package com.uduemc.biso.web.component;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.biso.core.extities.center.CustomerUser;
import com.uduemc.biso.core.extities.center.custom.CustomerUserRole;
import com.uduemc.biso.core.feign.CustomerFeign;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.web.details.CustomerUserDetails;

@Component
public class MyUserDetailsService implements UserDetailsService {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 可以注入具体的服务或者 mapper 主要是查询数据库的作用
	 */
	// @Autowired
	// private PasswordEncoder passwordEncoder;

	/**
	 * 获取用户的服务
	 */
	@Autowired
	private CustomerFeign customerFeign;

	@Autowired
	private ObjectMapper objectMapper;

	@SuppressWarnings("unchecked")
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		// 从数据库中获取用户信息
		RestResult restResult = customerFeign.getUserByUsername(username);
		if (restResult.getCode() != 200 || restResult.getData() == null) {
			logger.error("customerFeign.getByUsername(username); username:" + username
					+ " restResult.getCode() != 200 || restResult.getData() == null");
			throw new UsernameNotFoundException("用户名不存在!");
		}
		CustomerUser customerUser = null;
		try {
			customerUser = objectMapper.readValue(objectMapper.writeValueAsString(restResult.getData()),
					CustomerUser.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (customerUser == null || customerUser.getId().longValue() < 1L) {
			throw new UsernameNotFoundException("用户名不存在!");
		}
		logger.info(customerUser.toString());

		// 获取用户的权限
		restResult = customerFeign.findRoleById(customerUser.getId());
		if (restResult.getCode() != 200 || restResult.getData() == null) {
			logger.error("customerFeign.findRoleById(customerUser.getId()); customerUser.getId():"
					+ customerUser.getId() + " restResult.getCode() != 200 || restResult.getData() == null");
			throw new UsernameNotFoundException("用户名不存在!");
		}

		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class,
				CustomerUserRole.class);
		List<CustomerUserRole> findRoleByUsername = null;
		try {
			findRoleByUsername = (List<CustomerUserRole>) objectMapper
					.readValue(objectMapper.writeValueAsString(restResult.getData()), javaType);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (CollectionUtils.isEmpty(findRoleByUsername)) {
			findRoleByUsername = new ArrayList<>();
		}
		findRoleByUsername.add(0, new CustomerUserRole(0L, 0L, "访客", "guest"));

		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(findRoleByUsername.size());
		for (CustomerUserRole role : findRoleByUsername) {
			authorities.add(new SimpleGrantedAuthority(role.getRole()));
		}

		// 打印加密后的密文
		// System.out.println(passwordEncoder.encode("123456"));
		// 数据库中查出来的密码
		String password = customerUser.getPasswordHash();
		customerUser.setPasswordHash(null);

		// 用户可用(删除)
		boolean enabled = true;
		// 用户未冻结
		boolean accountNonLocked = true;
		CustomerUserDetails customerUserDetails = new CustomerUserDetails(username, password, enabled, true, true,
				accountNonLocked, authorities);

		customerUserDetails.setCustomerUser(customerUser);

		customerUserDetails.setCustomerUserRoles(findRoleByUsername);

		return customerUserDetails;
	}

}
